import { useCallback, useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { PullToRefresh, SpinLoading, InfiniteScroll } from 'antd-mobile'
import PageEmpty from '@components/pageEmpty'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import { getCaseList } from './ajax'
import { RightOutline } from 'antd-mobile-icons'
import classNames from 'classnames'
import { useAppDispatch } from '@src/redux/hook'
import { push } from '@src/redux/reducers/pages'
import uuid from 'uuid'

async function getList (list, current, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(current))
  setLoading(false)
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

async function loadMoreFn (list, current, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(current))
  setLoading(false)
  if (e !== null) {
    throw new Error(e.message)
  }
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

function Item ({ data }) {
  const dispatch = useAppDispatch()
  const [active, setActive] = useState(false)
  const date = useMemo(() => {
    return typeof data.release_datetime === 'number' && data.release_datetime > 0 ? formatDate(data.release_datetime, 'YYYY-MM-DD') : ''
  }, [data])
  return (
    <div className={classNames(style.item, {[style.active]: active})} onClick={() => {
      setActive(true)
      setTimeout(() => {
        setActive(false)
        if (typeof data.url === 'string' && data.url.length > 0) {
          window.open(data.url, '_blank')
        } else {
          dispatch(push({ element: 'newsDetail', title: '新闻详情', id: uuid(), meta: { id: data.id } }))
        }
      }, 150)
    }}>
      <div className={style.left}>
        <div className={style['item-title']}>{data.title}</div>
        {date && <div className={style['item-date']}>{date}</div>}
      </div>
      <RightOutline className={style.icon} />
    </div>
  )
}

function Main () {
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const hasMore = useMemo(() => {
      return list.length < total
    }, [total, list])
  const loadMore = useCallback(async () => {
    await loadMoreFn(list, list.length / 10 + 1, setList, setTotal, setLoading)
  }, [list])
  useEffect(() => {
    getList([], 1, setList, setTotal, setLoading)
  }, [])
  return (
    <PageComponent title='新闻列表'>
      <div className={style.container}>
        <PullToRefresh onRefresh={async () => {}}>
          {loading && list.length === 0 && (
            <div className={style.loading}>
              <SpinLoading />
            </div>
          )}
          {
            !loading && list.length === 0 && (
              <PageEmpty />
            )
          }
          <div className={style.list}>
            {
              list.map((li) => {
                return <Item key={li.id} data={li} />
              })
            }
          </div>
          {
            list.length > 0 && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          }
        </PullToRefresh>
      </div>
    </PageComponent>
  )
}

export default Main
